package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.dto.EntryDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.mapper.ApBehaviorEntryMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <p>
 * APP行为实体表,一个行为实体可能是用户或者设备，或者其它 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-03-17
 */
@Service
public class ApBehaviorEntryServiceImpl extends ServiceImpl<ApBehaviorEntryMapper, ApBehaviorEntry> implements IApBehaviorEntryService {

    @Override
    public ApBehaviorEntry getEntry(EntryDto dto) {
        // 如果userId不为空,根据userId查询
        if (dto.getUserId() != null) {
            LambdaQueryWrapper<ApBehaviorEntry> query = new LambdaQueryWrapper<>();
            query.eq(ApBehaviorEntry::getType, 1);
            query.eq(ApBehaviorEntry::getEntryId, dto.getUserId().toString());
            ApBehaviorEntry one = this.getOne(query);
            if (one != null) {
                return one;
            } else {
                // 第一次访问,新增行为实体并返回
                ApBehaviorEntry entry = new ApBehaviorEntry();
                entry.setType(1);
                entry.setEntryId(dto.getUserId().toString());
                entry.setCreatedTime(new Date());
                this.save(entry);
                return entry;
            }
        }
        // 如果设备id不为空,根据设备id查询
        if (!StringUtils.isEmpty(dto.getEquipmentId())) {
            LambdaQueryWrapper<ApBehaviorEntry> query = new LambdaQueryWrapper<>();
            query.eq(ApBehaviorEntry::getType, 0);
            query.eq(ApBehaviorEntry::getEntryId, dto.getEquipmentId());
            ApBehaviorEntry one = this.getOne(query);
            if (one != null) {
                return one;
            } else {
                // 第一次访问,新增行为实体并返回
                ApBehaviorEntry entry = new ApBehaviorEntry();
                entry.setType(0);
                entry.setEntryId(dto.getEquipmentId());
                entry.setCreatedTime(new Date());
                this.save(entry);
                return entry;
            }
        }
        return null;
    }
}
